/* eslint-disable */
const pako = require('pako')

function decode(data) {
	let isDecode = true;
	try {
		var node = parseXml(data).documentElement;
		console.log(node)
		if (node != null && node.nodeName === 'mxfile') {
			var diagrams = node.getElementsByTagName('diagram')
			if (diagrams.length > 0) {
				data = getTextContent(diagrams[0])
			}
		}
		if (node != null && node.nodeName === 'mxGraphModel') {
			//不需要转码
			isDecode = false;
			data = data
		}
	} catch (e) {
		// ignore
		console.log(e)
	}
	if (isDecode) {
		try {
			data = atob(data)
		} catch (e) {
			console.log(e)

			return
		}
		try {
			data = pako.inflateRaw(Uint8Array.from(data, c => c.charCodeAt(0)), {
				to: 'string'
			})
		} catch (e) {
			console.log(e)

			return
		}
		try {
			data = decodeURIComponent(data)
		} catch (e) {
			console.log(e)

			return
		}
	}



	return data
};

function parseXml(xml) {
	if (window.DOMParser) {
		var parser = new DOMParser()
		return parser.parseFromString(xml, 'text/xml')
	} else {
		var result = createXmlDocument()

		result.async = 'false'
		result.loadXML(xml)

		return result
	}
};

function createXmlDocument() {
	var doc = null
	if (document.implementation && document.implementation.createDocument) {
		doc = document.implementation.createDocument('', '', null)
	} else if (window.ActiveXObject) {
		// eslint-disable-next-line no-undef
		doc = new ActiveXObject('Microsoft.XMLDOM')
	}
	return doc
};

function getTextContent(node) {
	return (node != null) ? node[(node.textContent === undefined) ? 'text' : 'textContent'] : ''
};

export default decode
